<template>
  <div class="app-container">
    <el-menu
      mode="horizontal"
      text-color="#333333"
      active-text-color="#0b847b"
      :default-active="activeIndex"
      @select="handleSelect"
    >
      <el-menu-item index="1">项目列表</el-menu-item>
      <el-menu-item index="2">我的发布</el-menu-item>
      <el-menu-item index="3">草稿</el-menu-item>
    </el-menu>
    <div style="padding: 10px" />

    <el-card class="box-card">
      <div class="clearfix">
        <el-button type="primary" icon="el-icon-plus" @click="addNew">
          登记项目需求
        </el-button>
        <el-button type="danger" :disabled="!ids.length" @click="delInfo">
          批量删除
        </el-button>
        <el-form class="fr" inline>
          <el-form-item>
            <el-select
              v-if="params.type == 1"
              :value="params.range"
              placeholder="全部"
              @change="searchBtn"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>

      <el-table
        v-loading="listLoading"
        element-loading-text="Loading"
        :data="libraryArr"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="selection"
          align="center"
          :selectable="checkSelectable"
        />

        <el-table-column label="#" type="index" width="50px" align="center" />

        <el-table-column label="项目名称" align="center">
          <template slot-scope="scope">
            {{ scope.row.projectName ? scope.row.projectName : "--" }}
          </template>
        </el-table-column>

        <el-table-column label="目的及意义" align="center">
          <template slot-scope="scope">
            <span>
              <el-link
                v-if="
                  scope.row.projectCode && scope.row.projectCode.length > 50
                "
                type="primary"
                @click="
                  seeObjectiveDetails('目的及意义', scope.row.projectCode)
                "
                >查看详情</el-link
              >
              <span
                v-if="
                  scope.row.projectCode && scope.row.projectCode.length < 50
                "
                >{{ scope.row.projectCode }}</span
              >
            </span>
            <span v-if="params.type == 2">
              <el-link
                v-if="
                  scope.row.content.purpose &&
                  scope.row.content.purpose.length > 50
                "
                type="primary"
                @click="
                  seeObjectiveDetails('目的及意义', scope.row.content.purpose)
                "
                >查看详情</el-link
              >
              <span
                v-if="
                  scope.row.content.purpose &&
                  scope.row.content.purpose.length < 50
                "
                >{{ scope.row.content.purpose }}</span
              >
            </span>
          </template>
        </el-table-column>

        <el-table-column label="主要实施内容" align="center">
          <template slot-scope="scope">
            <p>
              <el-link
                v-if="scope.row.content && scope.row.content.length > 50"
                type="primary"
                @click="seeContent('主要实施内容', scope.row.content)"
                >查看详情</el-link
              >
              <span v-if="scope.row.content && scope.row.content.length < 50">
                {{ scope.row.content }}
              </span>
            </p>
            <p v-show="params.type == 2">
              <el-link
                v-if="
                  scope.row.content.content &&
                  scope.row.content.content.length > 50
                "
                type="primary"
                @click="seeContent('主要实施内容', scope.row.content.content)"
                >查看详情</el-link
              >
              <span
                v-if="
                  scope.row.content.content &&
                  scope.row.content.content.length < 50
                "
                >{{ scope.row.content.content }}</span
              >
            </p>
          </template>
        </el-table-column>

        <el-table-column label="实施周期" align="center">
          <template slot-scope="scope">
            {{ scope.row.projectCycle ? scope.row.projectCycle : "--" }}
          </template>
        </el-table-column>

        <el-table-column label="经费预期(万元)" align="center">
          <template slot-scope="scope">
            {{
              scope.row.projectFundsAmount ? scope.row.projectFundsAmount : "--"
            }}
          </template>
        </el-table-column>

        <el-table-column label="附件" align="center">
          <template slot-scope="scope">
            <p v-if="scope.row.projectAppendixUrl">
              <span
                v-for="(i, index) in scope.row.projectAppendixUrl"
                :key="index"
              >
                {{ i.fileName }}
              </span>
            </p>
            <p v-else>--</p>
          </template>
        </el-table-column>

        <el-table-column label="创建人" align="center">
          <template slot-scope="scope">
            {{ scope.row.createBy ? scope.row.createBy : "--" }}
          </template>
        </el-table-column>

        <el-table-column label="创建时间" align="center" width="170">
          <template slot-scope="scope">
            {{ scope.row.updateTime ? scope.row.updateTime : "--" }}
          </template>
        </el-table-column>

        <el-table-column label="标签" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.type == 2" style="color: #ef7045"
              >未立项</span
            >
            <span v-else>新建</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="180px" align="center">
          <template slot-scope="{ row }">
            <el-link type="info" @click="updateInfo(row, 1)">查看</el-link>

            <!-- 只有自己的才能进行编辑和删除 -->
            <el-link
              v-if="loginName == row.createBy"
              type="primary"
              @click="updateInfo(row, 2)"
            >
              编辑
            </el-link>
            <el-link
              v-if="params.type == 3"
              type="success"
              @click="submitDraft(row, 2)"
            >
              提交
            </el-link>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 表格 -->

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="params.pageNum"
      :limit.sync="params.pageSize"
      @pagination="getLibraryPage"
    />

    <!-- 对话框 -->
    <el-dialog
      :title="dialogTitle"
      width="40%"
      :visible.sync="isSHowDia"
      center
      :show-close="false"
      @close="beforeClose"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        label-width="120px"
        :rules="formRules"
        :model="xmProjectLibrary"
      >
        <el-form-item label="项目名称" prop="projectName">
          <el-input
            v-model="xmProjectLibrary.projectName"
            placeholder="请输入项目名称"
            :disabled="isShow"
          />
        </el-form-item>

        <el-form-item label="目的及意义" prop="projectCode">
          <el-input
            type="textarea"
            v-model="xmProjectLibrary.projectCode"
            placeholder="请输入目的及意义"
            :disabled="isShow"
          />
        </el-form-item>

        <el-form-item label="主要实施内容" prop="content">
          <el-input
            type="textarea"
            v-model="xmProjectLibrary.content"
            placeholder="请输入主要实施内容"
            :disabled="isShow"
          />
        </el-form-item>

        <el-form-item label="项目周期">
          <el-date-picker
            v-model="xmProjectLibrary.projectCycle"
            style="width: 100%"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :disabled="isShow"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="经费预算(万)">
          <el-input
            :min="min"
            :max="max"
            v-model="xmProjectLibrary.projectFundsAmount"
            type="number"
            placeholder="请输入经费预算"
            :disabled="isShow"
            @blur="blurProjectFundsAmount(xmProjectLibrary.projectFundsAmount)"
          />
        </el-form-item>

        <el-form-item label="附件">
          <el-upload
            :action="uploadUrl"
            :on-success="handleSuccess"
            :on-remove="onRemove"
            :headers="headers"
            :file-list="xmProjectLibrary.projectAppendixUrl"
            :disabled="isShow"
            :on-preview="onPreview"
          >
            <el-button icon="el-icon-plus" size="small" type="primary"
              >添加附件</el-button
            >
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('formRef')">取 消</el-button>
        <el-button type="primary" v-if="!isShow">
          <span
            v-if="params.type == 3"
            @click="submitInfo('formRef')"
            :loading="submitLoading"
            >保 存</span
          >
          <span v-else :loading="submitLoading" @click="submitInfo('formRef')"
            >提 交</span
          >
        </el-button>
      </div>
    </el-dialog>

    <el-dialog :title="conTtitle" :visible.sync="dialogVisible" width="30%">
      <span>{{ contain }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogVisible = false"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import moment from "moment";
import { uploadUrl } from "@/const";
import { getToken } from "@/utils/auth";
import { serverUrl } from "@/look";
import { Base64 } from "js-base64";

import {
  apiLibraryPage, // 项目库分页
  apiSaveLibrary, // 登记项目需求
  apiDelLibrary, // 删除
  apiGetDetails, // 获取详情
  apiUpdateLibrary, //修改
  apiPageCraft, //草稿列表
  apiDeleteCraft, //草稿箱删除
  apiCraftUpdateAndSubmit, // 修改提交
} from "@/api2/projectManagement/library";

export default {
  components: {},
  data() {
    return {
      min: 0,
      max: 9999999999,
      submitLoading: false,
      contain: "",
      dialogVisible: false,
      conTtitle: "",
      isShow: false, // 是否是查看
      formRules: {
        projectName: [
          { required: true, message: "请输入项目名称", trigger: "blur" },
        ],
        projectCode: [
          { required: true, message: "请输入目的及意义", trigger: "blur" },
        ],
        content: [
          { required: true, message: "请输入主要实施内容", trigger: "blur" },
        ],
      },
      options: [
        {
          value: 0,
          label: "我发布的",
        },
        {
          value: "",
          label: "全部",
        },
      ],
      value: "",
      uploadUrl,
      headers: {
        Authorization: getToken(),
        platform: 'WEB'
      },
      isSHowDia: false,
      ids: [], //是否多选
      activeIndex: "1",
      total: 0,
      libraryArr: [],
      params: {
        pageNum: 1,
        pageSize: 10,
        type: 1, //1是登记项目，2是未通过的项目
        range: "", //传0代表只查自己的 不传或者传别的查的就是全部
      },
      year: 0,
      dialogTitle: "登记项目需求",
      // --------
      xmProjectLibrary: {
        projectName: "",
        projectCode: "",
        content: "",
        projectFundsAmount: 0,
        projectAppendixUrl: [],
      },
      listLoading: false,
    };
  },
  computed: {
    loginName() {
      return JSON.parse(sessionStorage.getItem("loginUserinfo")).name;
    },
  },
  created() {
    this.handleSelect(1);
  },
  methods: {
    // 获取格式化时间字符串
    getFormatedTimeStr(stamp, str = "YYYY/MM/DD HH:mm") {
      return moment(stamp).format(str);
    },

    // 经费预算失去焦点事件
    blurProjectFundsAmount(val) {
      if (val < this.min) {
        this.xmProjectLibrary.projectFundsAmount = this.min;
      } else if (val > this.max) {
        this.xmProjectLibrary.projectFundsAmount = this.max;
      }
    },

    // 点击文件列表中已上传的文件时的钩子
    onPreview(file) {
      console.log(file);
      window.open(
        serverUrl +
          "onlinePreview?url=" +
          encodeURIComponent(Base64.encodeURI(file.url))
      );
    },

    // 仅对 type=selection 的列有效，类型为 Function，Function 的返回值用来决定这一行的 CheckBox 是否可以勾选
    checkSelectable(row) {
      let loginName = JSON.parse(sessionStorage.getItem("loginUserinfo")).name;
      return row.createBy == loginName;
    },

    // 查看目的和内容详情
    seeObjectiveDetails(title, contain) {
      this.dialogVisible = true;
      this.conTtitle = title;
      this.contain = contain;
    },
    seeContent(title, contain) {
      this.dialogVisible = true;
      this.conTtitle = title;
      this.contain = contain;
    },

    // 删除上传的附件
    onRemove(file) {
      let data = this.xmProjectLibrary.projectAppendixUrl;
      for (let i = 0; i < data.length; i++) {
        if (file.uid == data[i].uid) {
          data.splice(i, 1);
        }
      }
    },

    handleClose() {
      this.isSHowDia = false;
    },
    beforeClose() {
      this.isSHowDia = false;
      this.xmProjectLibrary = {
        projectName: "",
        projectCode: "",
        content: "",
        projectFundsAmount: 0,
        projectAppendixUrl: [],
      };

      if (this.params.type == 3) {
        this.getPageCraft();
      } else {
        this.init();
      }
    },

    // ApiGetDetails(){
    //   apiGetDetails().then().catch()
    // },

    // 查看
    // 编辑 按钮
    updateInfo(row, i) {
      this.xmProjectLibrary = row;
      let obj = row;
      // 项目列表
      if (this.params.type == 2) {
        this.xmProjectLibrary.projectCycle = [,];
        this.xmProjectLibrary.projectAppendixUrl = [];
        this.xmProjectLibrary.projectCode = obj.content.purpose; //目的和意义
        this.xmProjectLibrary.content = obj.content.content; //主要实施内容
      } else {
        // 处理附件`
        for (let i = 0; i < row.projectAppendixUrl.length; i++) {
          this.xmProjectLibrary.projectAppendixUrl[i].name =
            row.projectAppendixUrl[i].fileName;
        }
        // 处理时间
        // 将返回的时间"2023/04/14-2023/04/15" 转为['2023-04-14','2023-04-15']
        const dateString = row.projectCycle;
        if (dateString) {
          const dateArray = dateString.split("-");
          this.xmProjectLibrary.projectCycle = dateArray.map((date) =>
            date.replace(/\//g, "-")
          );
        }
      }

      this.isSHowDia = true;
      if (i == 1) {
        this.dialogTitle = "查看";
        this.isShow = true;
      } else {
        this.dialogTitle = "编辑";
        this.isShow = false;
      }
    },

    // 删除项目库
    delInfo() {
      let id = this.ids.join(",");
      this.$confirm("是否确认删除选中数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          if (this.params.type == 3) {
            apiDeleteCraft(this.ids)
              .then((res) => {
                if (res.code === 0) {
                  this.msgSuccess("删除成功");
                  this.getPageCraft();
                } else {
                  this.msgError("删除失败");
                }
              })
              .catch(() => {
                this.msgError("删除失败");
              });
          } else {
            apiDelLibrary(id)
              .then((res) => {
                if (res.code === 0) {
                  this.msgSuccess("删除成功");
                  this.init();
                } else {
                  this.msgError("删除失败");
                }
              })
              .catch(() => {
                this.msgError("删除失败");
              });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },

    // 取消
    resetForm() {
      this.isSHowDia = false;
      this.xmProjectLibrary.projectCycle = [,];
      this.isShow = false;
    },

    // 草稿箱提交
    submitDraft(row) {
      apiCraftUpdateAndSubmit(row.libraryId)
        .then((res) => {
          if (res.code == 0) {
            this.msgSuccess("提交成功");
            this.getPageCraft();
          } else {
            this.msgError("提交失败");
          }
        })
        .catch((err) => {
          console.log(err);
          this.msgError("提交失败");
        });
    },

    // 提交
    submitInfo(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.submitLoading = true;
          let data = {
            projectName: this.xmProjectLibrary.projectName,
            projectCode: this.xmProjectLibrary.projectCode,
            content: this.xmProjectLibrary.content,
            projectFundsAmount:
              this.xmProjectLibrary.projectFundsAmount == ""
                ? 0
                : this.xmProjectLibrary.projectFundsAmount,
          };
          if (
            this.xmProjectLibrary.projectCycle &&
            this.xmProjectLibrary.projectCycle.length == 2
          ) {
            data.projectCycle =
              this.getFormatedTimeStr(this.xmProjectLibrary.projectCycle[0]) +
              "-" +
              this.getFormatedTimeStr(this.xmProjectLibrary.projectCycle[1]);
          }
          // 操作附件地址
          let urlArr = [];
          if (this.xmProjectLibrary.projectAppendixUrl.length) {
            urlArr = this.xmProjectLibrary.projectAppendixUrl.map((v) => {
              return {
                fileName: v.fileName,
                relativeFilePath: v.relativeFilePath,
                size: v.size,
                suffix: v.suffix,
                url: v.url,
              };
            });
          }
          if (urlArr.length) {
            data.projectAppendixUrl = JSON.stringify(urlArr);
          } else {
            data.projectAppendixUrl = "[]";
          }

          if (this.xmProjectLibrary.libraryId) {
            data.libraryId = this.xmProjectLibrary.libraryId;
            apiUpdateLibrary(data)
              .then((res) => {
                this.submitLoading = false;
                if (res.code == 0) {
                  this.msgSuccess("修改成功");
                  this.resetForm();
                  this.init();
                } else {
                  this.msgError("修改失败");
                }
              })
              .catch((err) => {
                this.submitLoading = false;
                console.log(err);
                this.msgError("修改失败");
              });
          } else {
            apiSaveLibrary(data)
              .then((res) => {
                this.submitLoading = false;
                if (res.code == 0) {
                  this.msgSuccess("提交成功");
                  this.resetForm();
                  this.init();
                } else {
                  this.msgError("提交失败");
                }
              })
              .catch((err) => {
                this.submitLoading = false;
                console.log(err);
                this.msgError("提交失败");
              });
          }
        } else {
          return false;
        }
      });
    },

    // 搜索
    searchBtn(val) {
      this.$set(this.params, "range", val);
      this.init();
    },

    // 上传附件
    handleSuccess(res) {
      if (res.code === 0) {
        this.xmProjectLibrary.projectAppendixUrl.push(res.data);
        for (
          let i = 0;
          i < this.xmProjectLibrary.projectAppendixUrl.length;
          i++
        ) {
          this.xmProjectLibrary.projectAppendixUrl[i].name =
            this.xmProjectLibrary.projectAppendixUrl[i].fileName;
        }
      } else {
        this.msgError("上传失败");
        this.xmProjectLibrary.seriesCoverUrl = [];
      }
    },

    // 新增按钮
    addNew() {
      this.isSHowDia = true;
      this.dialogTitle = "登记项目需求";
    },

    // 草稿列表
    getPageCraft() {
      apiPageCraft()
        .then((res) => {
          if (res.code === 0) {
            this.total = res.total;
            this.libraryArr = res.data;
            // 新增的数据有附件
            if (this.params.type == 3) {
              for (let i = 0; i < this.libraryArr.length; i++) {
                this.libraryArr[i].projectAppendixUrl =
                  JSON.parse(this.libraryArr[i].projectAppendixUrl) ?? [];
              }
            }
          } else {
            this.total = 0;
            this.libraryArr = [];
          }
          this.listLoading = false;
        })
        .catch();
    },

    // 切换tab
    handleSelect(e) {
      this.params.type = e;
      let loginUser = JSON.parse(sessionStorage.getItem("loginUserinfo")).name;
      if (e == 1 || e == 2) {
        // 项目列表-科管院/普通用户
        if (e == 1) {
          this.params.range = loginUser == "科研管理员" ? "" : 0;
          this.init();
          return;
        }
        // 我的发布
        if (e == 2) {
          this.params.range = 0;
          this.init();
          return;
        }
      } else {
        this.getPageCraft();
      }
    },

    // 判断批量删除
    handleSelectionChange(val) {
      this.ids = val.map((item) => item.libraryId);
    },

    getLibraryPage() {
      this.listLoading = true;
      apiLibraryPage(this.params)
        .then((res) => {
          if (res.code === 0) {
            this.total = res.total;
            this.libraryArr = res.data;
            // 新增的数据有附件
            if (this.params.type == 1) {
              for (let i = 0; i < this.libraryArr.length; i++) {
                this.libraryArr[i].projectAppendixUrl =
                  JSON.parse(this.libraryArr[i].projectAppendixUrl) ?? [];
              }
            }

            // 自立项目 content 比较复杂
            if (this.params.type == 2) {
              for (const i of this.libraryArr) {
                if (
                  i.content[0] == "{" &&
                  i.content[i.content.length - 1] == "}"
                ) {
                  i.content = JSON.parse(i.content);
                }
              }
            }
          } else {
            this.total = 0;
            this.libraryArr = [];
          }
          this.listLoading = false;
        })
        .catch((err) => {
          console.log(err);
          this.total = 0;
          this.libraryArr = [];
          this.listLoading = false;
        });
    },

    init() {
      this.getLibraryPage();
    },
  },
};
</script>

<style lang="scss" scoped>
.el-link {
  margin: 0 0.5rem;
}
.app-container {
  width: 100%;
  height: 100%;
  background: #f4f5fc;
}
.right {
  display: flex;
  align-items: center;
  justify-content: center;
}
::v-deep .el-dialog__header {
  text-align: left;
}
::v-deep .el-upload {
  text-align: left;
}
</style>
